using System;
using System.Collections.Generic;
using System.Linq;
using Arcane.Source.Story.Transitions;
using Godot;

namespace Arcane.Source.Story
{
    public partial class DialogHandler : Control, IDialogHandler
    {
        private static StringName SELECTION_CREATE_FUNC = "make_selections";
        [Export]
        private Label _content;
        [Export]
        private Label _charaName;
        [Export]
        private Control _selectionButtonGroup;

        
        public event Action<string[]> OnDialogEnd;
        public event Action<IDialogTransition> ProcessTransition;

        private Dialog _dialog;
        private readonly List<string> _selections = [];

        public void ShowDialog(Dialog dialog)
        {
            _dialog = dialog;

            Visible = true;
            _selectionButtonGroup.Visible = false;

            if (_dialog.selections?.Count > 0)
            {
                ShowSelections(_dialog.selections);
            }

            _charaName.Text = _dialog.character;
            _content.Text = _dialog.message;
        }

        public void ShowSelections(Dictionary<string, IDialogTransition> selections)
        {
            _selectionButtonGroup.Visible = true;
            var gd = new Godot.Collections.Dictionary();
            foreach (var (k, v) in selections)
            {
                gd.Add(k, Callable.From(() =>
                {
                    if (v != null)
                    {
                        // ShowCurrent();
                        ProcessTransition?.Invoke(v);
                        _selections.Add(k);
                    }
                }));
            }
            _selectionButtonGroup.Call(SELECTION_CREATE_FUNC, gd);
        }

        public void OnRequestNext()
        {
            if (_dialog.selections?.Count > 0) return;

            if (_dialog.defaultNext != null)
            {
                // ShowCurrent();
                ProcessTransition?.Invoke(_dialog.defaultNext);
                _selections.Add(null);
            }
            else
            {
                OnDialogEnd?.Invoke([.. _selections]);
                OnDialogEnd -= OnDialogEnd;
            }
        }
    }
}